package com.app.web.jst.job;

import com.app.base.EnumType;
import com.app.utils.base.j2se.*;
import com.app.utils.jst.JstEnum;
import com.app.utils.jst.JstHandler;
import com.app.utils.jst.paramBean.OrderSearchParam;
import com.app.web.order.OrderDao;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class OrderSync implements Job {
    @Autowired
    private OrderDao orderDao;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Logger.info("---------------OrderSync--更新订单快递信--begin");
        if(!Logger.isOnline()){
            Logger.info("更新订单快递信---当前环境为研发环境----结束");
            return;
        }
        LocalDateTime end = LocalDateTime.now();
        LocalDateTime begin = end.minusMinutes(10);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        OrderSearchParam param = OrderSearchParam.builder().shop_id(15373400).modified_begin(formatter.format(begin)).modified_end(formatter.format(end)).status(JstEnum.status.已发货.getStatus()).build();

        Map<String,Object> res = JstHandler.execute(JstEnum.Url.订单查询.getUri(), JsonUtil.toJson(param));
        if(StringHandler.isEmpty(res)){
            Logger.info("---------------OrderSync--更新订单快递信--没有已发货商品--end");
            return;
        }
        Map<String, Object> data = (Map<String, Object>) res.get("data");
        if(Convert.objToInt(data.get("data_count"))>0){
            List<Map<String,Object>> datas = (List<Map<String, Object>>) data.get("orders");
            datas.forEach(x->{
                //有快递单号代表发货,更新快递单号，发货日期，快递公司名
                if(Common.isNotEmpty(x.get("l_id"))){
                    Map<String,Object> map = new HashMap<String, Object>(){{
                        put("l_id",x.get("l_id"));
                        put("send_date",x.get("send_date"));
                        put("logistics_company",x.get("logistics_company"));
                        put("order_sn",x.get("so_id"));
                        put("date", DateUtil.getDate());
                        put("status", EnumType.ORDER_STATUS.已发货.getStatus());
                    }};
                    int i = orderDao.orderSync(map);
                    if(i!=1){
                        Logger.error("更新订单快递信息异常，订单号："+x.get("so_id"));
                    }
                }
            });
        }else{
            Logger.info("---------------OrderSync--更新订单快递信--没有已发货商品--data_count=0--end");
            return;
        }
        Logger.info("---------------OrderSync--更新订单快递信--end");
    }
}
